昨天有了隔線,接著就是要弄拼圖出來
首先先定義一些顏色
gem_imgs = {
'blue': (0, 0, 255),
'red': (255, 0, 0),
'green': (0, 255, 0),
'purple': (100, 0, 255),
'yellow': (100, 255, 0),
'orange': (255, 100, 0),
}
gem_imgs_list = list(gem_imgs.keys())
接著定義拼圖物件
class Puzzle(pygame.sprite.Sprite):
def __init__(self, color, position, downlen):
pygame.sprite.Sprite.__init__(self)
self.color = color
self.image = pygame.Surface((GRIDSIZE - 4, GRIDSIZE - 4))
self.image.fill(gem_imgs[color])
self.rect = self.image.get_rect(center = position)
self.rect.x = position[0] + 2
self.rect.y = position[1] + 2
self.downlen = downlen
這邊的image也可以用現成的圖片來代替,寫法上就要替換成這樣
img = pygame.image.load(img_path)
self.image = pygame.transform.scale(img, (GRIDSIZE, GRIDSIZE))
self.rect = img.get_rect()
接下來定義拼圖生成的方法
def put_puzzle(self):
# 所有的拼圖物件都會放在self.all_gems裡面,通常要引用拼圖方法都會呼叫這邊
self.all_gems = []
# 這邊我沒有很清楚sprite.Group的方法,看起來是所有遊戲物件的集合
self.gems_group = pygame.sprite.Group()
for x in range(NUMGRID):
self.all_gems.append([])
for y in range(NUMGRID):
gem = Puzzle(color=random.choice(gem_imgs_list), position=[XMARGIN+x*GRIDSIZE, YMARGIN+y*GRIDSIZE], downlen=NUMGRID*GRIDSIZE)
self.all_gems[x].append(gem)
self.gems_group.add(gem)
這時候來把畫面運作起來
好的看起來有個樣子了
接下來定義滑鼠的點擊事件,這邊我先去抓出事件的座標位置
left_mouse_pressed = False
for event in pygame.event.get():
# 不知為何絕對要有這行才跑得動
if event.type == pygame.QUIT: sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
# 判斷左鍵按壓
if pygame.mouse.get_pressed()[0] == True:
press_pos = pygame.mouse.get_pos()
left_mouse_pressed = True
print(press_pos)
elif event.type == pygame.MOUSEBUTTONUP:
# 判斷左鍵釋放
if left_mouse_pressed == True:
left_mouse_pressed == False
release_pos = pygame.mouse.get_pos()
print(release_pos)
運作之後在視窗上點點看看
到這邊吧,這進度看起來是非常落後...
明天會來寫拼圖轉換與消除的功能